package com.myProject.filter;

import com.myProject.bean.TUser;
import com.myProject.serves.Impl.UserSevImpl;
import com.myProject.serves.UserSev;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebFilter(filterName = "LoginFilter", urlPatterns = "*.html")
public class LoginFilter implements Filter {
    UserSev us = new UserSevImpl();

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("LoginFilter doFilter");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String url = request.getRequestURI();
        System.out.println("请求的url：" + url);
        //登录页面不需要过滤
        int idx = url.lastIndexOf("/");
        String endWith = url.substring(idx + 1);
        if (!"login.html".equals(endWith) && !"register.html".equals(endWith)) {
            //不是登录页面  进行拦截处理
            System.out.println("不是登录或者注册页面，进行拦截处理");

            if (!isLogin(request)) {
                System.out.println("没有登录过或者账号密码错误，跳转到登录界面");
                response.sendRedirect("login.html");
            } else {
                System.out.println("已经处在登录状态，进行下一步");
                chain.doFilter(req, resp);
            }
        } else {
            System.out.println("是登录页面，不进行拦截处理");
            chain.doFilter(req, resp);
        }

    }

    private boolean isLogin(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String user = "";

        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("loginName".equals(cookie.getName())) {
                    user = cookie.getValue();
                }
            }
        }

        TUser tUser = new TUser();
        tUser.setUser(user);

        //获得当前登录的对象
        List<TUser> list = us.loginUserName(tUser);

        if ("".equals(user)) {
            return false;
        }

        if (user.equals(list.get(0).getUser())) {
            System.out.println("登录用户名字=" + list.get(0).getUser());
            System.out.println("登录用户密码 = " + list.get(0).getPassword());
            return true;
        }
        return false;
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
